import csv
import os
import codecs
from pymongo import MongoClient

client = MongoClient('localhost', 27017)

qiancheng_db = client['qiancheng_db']
qiancheng_posts, qiancheng_corps = qiancheng_db['qiancheng_posts'], qiancheng_db['qiancheng_corps']


def pack(collection, file_name):
    industry_list = ['证券', '银行', '客服', '销售', '产品', '技术', '会计', '教育', '法律', '汽车', '医药', '化工']

    for industry in industry_list:
        csv_file = codecs.open("backup/" + file_name + '/' + file_name + '-' + industry + '.csv', 'w', 'utf_8_sig')

        header_item = collection.find_one()

        del header_item['_id']
        del header_item['url']
        del header_item['toSchool']
        del header_item['stime']

        header_item['company_type'] = ''
        header_item['company_industry'] = ''

        headers = [k for k in header_item]

        writer = csv.DictWriter(csv_file, fieldnames = headers)
        writer.writeheader()

        data = qiancheng_posts.find({'subIndustry': industry})

        for job in data:
            comp = qiancheng_corps.find_one({'name': job['company']})

            job['company_type'] = comp['type']
            job['company_industry'] = comp['industry']

            del job['_id']
            del job['url']
            del job['toSchool']
            del job['stime']

            writer.writerow(job)

        csv_file.close()


pack(qiancheng_posts, '前程无忧')
